package com.wangyadong.hobby.javanetwork.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NIOServerDemo {


    public static void main(String[] args) {
        try {
            //构建服务器监听程序
            ServerSocketChannel open = ServerSocketChannel.open();
            ServerSocket socket = open.socket();
            //绑定端口
            SocketAddress address = new InetSocketAddress(29);
            socket.bind(address);
            //设置非阻塞
            open.configureBlocking(false);
            //构建选择器
            Selector selector = Selector.open();
            //将选择器注册到ServerSocketChannel中，进而selector 做复用
            open.register(selector, SelectionKey.OP_ACCEPT);

            while (true) {
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey next = iterator.next();
                    SelectableChannel channel = next.channel();
                    if (next.isAcceptable()) {
                        System.out.println("accetp from the " + channel);
                        //服务器接口请求
                        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) channel;
                    } else if (next.isWritable()) {
                        SocketChannel socketChannel = (SocketChannel) channel;

                    }
                }
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
